﻿var currenContent = "uncnown";
var campars = "";
var firstpublish = 0;
function gete(ob) {
    var rt = null;
    var rt = document.getElementById(ob);
    if (null == rt) {
        rt = document.getElementsByName(ob);
    }
    return rt;
}
function waitTimeOut(timeset) {

    var ctimeset = timeset * 1000;
    if (ctimeset > 30000)
        ctimeset = 30000;
    if (ctimeset > 0) {
        setTimeout("window.location.reload()", ctimeset);
    }
}
//
function addppublicator(myn, url, para) {
    AC_FL_RunContent(
                                         'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=11,2,0,0',
                                         'width', '100%',
                                         'height', '100%',
                                     'src', window.MAIN_WEB_PATH + 'Content/flash/VSPublishPlayer',
                                         'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
                                         'wmode', 'window',
                                         'bgcolor', '#c4c4c4',
                                         'wmode',"opaque",
                                         'name', myn,
                                         'allowFullScreen', 'true',
                                         'allowScriptAccess', 'sameDomain',
                                         'movie', window.MAIN_WEB_PATH + 'Content/flash/VSPublishPlayer',
                                         'id', myn,
                                         'flashvars', 'myname=' + myn + '&amp;srvAddr=' + url + '&amp;' + para
                                         )
}
function addonlineplayer(myn, url, para) {
    
    AC_FL_RunContent(
                                         'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=11,2,0,0',
                                         'width', '100%',
                                         'height', '100%',
                                         'src', window.MAIN_WEB_PATH + 'Content/flash/VSLivePlayer',
                                         'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
                                         'wmode', 'window',
                                         'bgcolor', '#c4c4c4',
                                         'wmode', "opaque",
                                         'name', myn,
                                         'allowFullScreen', 'true',
                                         'allowScriptAccess', 'always',
                                         'movie', window.MAIN_WEB_PATH + 'Content/flash/VSLivePlayer',
                                         'id', myn,
                                         'flashvars', 'myname=' + myn + '&amp;srvAddr=' +url + '&amp;' + para
                                         )
}
//
    function addpplayer(oname, url, userID, sessionID, videoID,skn, ev) {
    
    var e = "";
    var s = "";
    if (skn && skn != "")
        s = "Y";
    
    var pname = "VSLivePlayer";
    if (s != "")
        pname = "VSOfflinePlayer";
    if (ev)
        e = ev;
    
    AC_FL_RunContent(
                                         'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=11,2,0,0',
                                         'width', '100%',
                                         'height', '100%',
                                         'src', window.MAIN_WEB_PATH + 'Content/flash/'+pname,
                                         'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
                                         'wmode', 'window',
                                         'bgcolor', '#c4c4c4',
                                         'wmode', "opaque",
                                         'name', oname,
                                         'allowFullScreen', 'true',
                                         'allowScriptAccess', 'always',
                                         'movie', window.MAIN_WEB_PATH + 'Content/flash/'+pname,
                                         'id', oname,
                                         'flashvars', 'myname=' + oname + '&amp;videoID=' + videoID + '&amp;userID='
                                         + userID + '&amp;userSession=' + sessionID + '&amp;srvAddr=' + url + '&amp;' + e
                                         )
}
function createMeeting(pname, meetingID, meetingName, maxUsers) {
    var flashPlayer = gete(pname);
    if (flashPlayer) {
        setPass(pname);
        flashPlayer.callPlayer(action);
    }
}

//
function liveplay(pname, _action, attempt) {
   
    attempt = attempt || 2;
    var action = _action;
    var flashPlayer = gete(pname);
    if (null != flashPlayer && flashPlayer.callPlayer) {
        if (action == "play")
            setPass(pname);
        flashPlayer.callPlayer(action);
     }
    else {
        attempt = attempt - 1;
        if (attempt > 0) {
            setTimeout('liveplay("'+pname+'", "'+action+'",'+attempt+')', 2000);
        }
    }
 
}
function goMeeting(myi, mname, cnt, _psw) {
   // alert(myi + "/" + mname + "/" + cnt + "/" + psw);
    var c = cnt;
    var passV = gete("meet_mypass");
    var i = 0;
    var z = 0;
    var myn = "";
    var nam = "";
    var psw = "";
    if (passV) {
        psw = passV.value;
        for (i = 0; i < c; i++) {
            myn = mname + "_" + i;
            if (myn != myi) {
                z = z + 1;
                nam = "meeting_pl_" + z;
                goPlayerMeeting(nam, psw, myn);
            }
        }
    }
}
function goPlayerMeeting(pname, pass, strm) {
    var flashPlayer = gete(pname);
    if (flashPlayer.setPass && flashPlayer.callPlayerM) {
        flashPlayer.setPass(pass);
        flashPlayer.callPlayerM(strm);
    }
}
function actionCamera(pname, opType) {
    if (!opType) {
        return;
    }
    var flashPlayer = gete(pname);
    if (null != flashPlayer) {

        if (opType == "connect") {
            flashPlayer.cameraConnect();
        }
        else
            if (opType == "disconnect")
                flashPlayer.cameraDisconnect();
            else
                if (opType == "full") {
                    var y = gete(pname + '_flashdiv');
                    var w = gete(pname + '_cwidth');
                    var h = gete(pname + '_cheight');
                    //  var f = document.getElementById(pname+'_cfps');
                    if (y && w && h) {
                        y.style.width = w.value + 'px';
                        y.style.height = h.value + 'px';
                    }
                    //            flashPlayer.cameraFull();
                }
    }
}
//             var s = z.innerHTML.split('x');
//             if (s.length  == 3)
function publishCamera(pname, contentID) {

    if (firstpublish == 1) {
        $("#confirm-publish-msg").dialog('open');
        return;
    }
    setPass(pname);
    if (paydForPublish(contentID))
        return;
    var flashPlayer = gete(pname);
    if (null != flashPlayer && flashPlayer.publishVideo) {


        flashPlayer.publishVideo();
    }

}
function paydForPublish(onlineContentId) {


    $.ajax({
        type: "POST",
        url: window.MAIN_WEB_PATH + "Ajax/PayForContentPublish",
        dataType: "json",
        data: { onlineContentId: onlineContentId },
        success: function (data, textStatus, jqXHR) {
            if (data) {
                if (data == "YP" || data == "YA")
                    return true;
                else
                    return false;
            }
            else
                return false;

        },
        error: function (data, textStatus, jqXHR) { return false; }
    });
}
function setPass(pname) {
    var flashPlayer = gete(pname);
    
    if (flashPlayer != null && flashPlayer.setPass) {
        var passV = gete("meet_mypass");
       
        if (null !=passV && passV) {
            flashPlayer.setPass(passV.value);
        }
    }
}
function playerMsg(pname, msg, idmsg) {
    if (idmsg == 9001) {
        setText(pname + "_msg", msg);
        return;
    }
    if (msgsF && msgsF[idmsg])
        setText(pname + "_msg", msgsF[idmsg]);
   // else
  //      setText(pname + "_msg",idmsg+"="+ msg);
}

function unpublishCamera(pname) {
    var flashPlayer = gete(pname);
    if (null != flashPlayer) {
        flashPlayer.unpublishVideo();
    }
}
//
//pna - player ID 
//cwidth - width
//cheight - height
//cfps - frames per second
//cfavorArea - true = size priority, false = fps priority 
//
function camera_setMode(pname, cwidth, cheight, cfps, cfavorArea) {
    var flashPlayer = gete(pname);

    if (null != flashPlayer) {
        flashPlayer.camera_setMode(parseInt(cwidth), parseInt(cheight), parseInt(cfps), Boolean(cfavorArea));
    }
}
function camera_applyMode(pname) {
    var w = gete(pname + '_cwidth');
    var h = gete(pname + '_cheight');
    var f = gete(pname + '_cfps');
    var a = gete(pname + '_fwa');
    if (w && h && f && a) {
        camera_setMode(pname, w.value, h.value, f.value, a.checked);
    }
}
function camera_setQuality(pname, bw, fq, kfi) {
    var flashPlayer = gete(pname);

    if (null != flashPlayer) {
        flashPlayer.camera_setQuality(parseInt(bw), parseInt(fq), parseInt(kfi));
    }
}
function camera_applyQuality(pname) {
    var bw = gete(pname + '_bw');
    var fq = gete(pname + '_fq');
    var kfi = gete(pname + '_kfi');
    if (bw && fq && kfi) {
        camera_setQuality(pname, bw.value, fq.value, kfi.value);
    }
}

function setText(nameob, stext) {

    var docs = null;
    docs = gete(nameob);
    if (!docs)
        docs = gete(nameob);
    if (null != docs) {
        docs.innerHTML = stext;
    }

}
function setBg(nameob, colorob) {
    var ob = gete(nameob);
    if (ob)
        ob.style.backgroundColor = colorob;
}
function playCallback(flashID, ffcode, fstring) {
    var pub = flashID
    var fcode = ffcode + 0;
    //проверяем от кого получено
    switch (pub) {
        case 'pub1':
            // делаем что-нибудь если надо
            break;
    }


    switch (fcode) {
        case -1001:
            //"No Camera Found"
            break;
    }
}
function chDisplayI(o, v, st, ht) {
    var obj = gete(o);
   
    if (null != obj) {
        if (obj.style.display == 'none') {
            obj.style.display = 'block';
            if (v)
                v.innerHTML = st;
        }
        else {
            obj.style.display = 'none';
            if (v)
                v.innerHTML = ht;

        }
    }
}

function chDisplay(o) {
    var obj = gete(o);

    if (null != obj) {
        if (obj.style.display == 'none')
            obj.style.display = 'block';
        else
            obj.style.display = 'none';
    }
}
function showhide(o, show) {
    var obj = gete(o);

    if (null != obj && obj.style)
        obj.style.display = show;

}
function flashCallback(flashID, ffcode, fstring) {
    
    var fcode = parseInt(ffcode, 10);
    var pub = flashID
    //проверяем от кого получено
    switch (fcode) {

        case -1001:
            playerMsg(pub, "Camera not found or disabled. Please connect camera", fcode);
            break;
        case -1002:
            //No Microphone Found"
            break;
        case 1001:
            //"Camera Found"
            break;
        case 1002:
            //Microphone Found"
            break;
        case 2001:
            //set resolution fstring = WxXxFPS
            var w = gete(pub + '_cwidth');
            var h = gete(pub + '_cheight');
            var f = gete(pub + '_cfps');
            if (w && h && f) {
                var s = fstring.split('x');
                if (s.length == 3) {
                    w.value = s[0];
                    h.value = s[1];
                    f.value = s[2];
                }

            }
            //alert(fstring);
            setText (pub+"_camera_param",fstring);
            break;
        case 2011:
            //set quality
            var bw = gete(pub + '_bw');
            var fq = gete(pub + '_fq');
            var kfi = gete(pub + '_kfi');
            if (bw && fq && kfi) {
                var s = fstring.split('x');
                if (s.length == 3) {
                    bw.value = s[0];
                    fq.value = s[1];
                    kfi.value = s[2];
                }

            }
            //var a = document.getElementById(pub+'_fwa');
            //            setText (pub+"_camera_param",fstring);
            break;
        case 2002:
            // showhide(pub + '_ofcambtn', 'block');
            // showhide(pub + '_oncambtn', 'none');
            showhide(pub + '_publish', 'block');
            showhide(pub + '_unpublish', 'none');
           // camera_applyMode(pub);
           // camera_applyQuality(pub);
            playerMsg(pub, "To start the broadcast, click on the 'Start broadcasting'", fcode);
          //  alert(campars);
            sendCamParam(pub, campars, 'camPresets');
            
            // setBg(pub+"_camstatus","#0d0");
            //camera connected
            break;
        case 2003:
            playerMsg(pub, "To continue the broadcast, click on the 'Start broadcasting'", fcode);
            showhide(pub + '_publish', 'block');
            showhide(pub + '_unpublish', 'none');
            //  showhide(pub + '_ofcambtn', 'none');
            //  showhide(pub + '_oncambtn', 'block');
            //camera disconnected
            break;
        case -3000:
            //ошибка при публикации
            break;
        case -3100:
            //-3100 -3199 внутренняя ошибка при публикации - камера не подключена, нет связи с сервером и т.п.
            break;
        case -3001:
            //адрес сервера не задан
            break;
        case -3200:
            // отказано в публикации: недостаточно прав, исчерпан лимит на количество,  уже опубликовано и т.п
            break;
        case -3300:

            playerMsg(pub, "To start the broadcast you must set a password. Please enter password.", fcode);
            //password need
            break;
        case -3301:
            //короткий пароль
            break;
        case 3301:
            //пароль задан
            break;
        case -3400:
            //зарезервировано
            break;
        case -3500:
            //зарезервировано
            break;
        case 3000:
            //старт соединения с сервером
            break;
        case 3001:
            playerMsg(pub, "Server connected. Start publishing...", fcode);
            //соединение с сервером установлено
            break;
        case 3002:
            showhide(pub + '_publish', 'none');
            showhide(pub + '_unpublish', 'block');
            showhide('cancelPublishing', 'block');
            
            playerMsg(pub, "Live webcam. On Air.", fcode);
            showhide("chat_block", "block");
            if (startMyTranslateTimer)
                startMyTranslateTimer();
            showhide(pub + '_settings_btn', 'none');

            //if (pub=""currenContent == 'Conference')
            //    liveplay("live1C", "play");
            //публикация стартовала
            break;
        case 3092:
            showhide(pub + '_publish', 'none');
            showhide(pub + '_unpublish', 'block');
            showhide('cancelPublishing', 'block');

            playerMsg(pub, "Connected. On Air.", fcode);
            showhide("chat_block", "block");
            showhide(pub + '_settings_btn', 'none');

            break;
        case 3102:
            showhide(pub + '_publish', 'block');
            showhide(pub + '_unpublish', 'none');
            playerMsg(pub, "Pause publishing. Click PUBLISH for start.", fcode);
            //
            break;

        case 5000:
            playerMsg(pub, "Connect to server...", fcode);
            //live player start connection
            break;
        case 5001:
            //server connected
            playerMsg(pub, "Server connected...", fcode);
            break;
        case -5001:
            //error connect to server
            playerMsg(pub, "Error on connect to server.", fcode);
            break;
        case -5300:
            playerMsg(pub, "Password protection. Please enter password.", fcode);
            //password need
            break;
        case -5302:
            playerMsg(pub, "Incorrect password.", fcode);
            //password incorrect
            break;
        case -5002:
            playerMsg(pub, "You cannot connect more than one broadcast at the same time", fcode);
            break;
        case 5002:
            //play live video started
            if (pub == "prePLAY")
                waitclos = setTimeout("noframe()", 3000);

            //   showhide(pub + '_playbtn', 'none');
            //    showhide(pub + '_stopbtn', 'block');
            playerMsg(pub, "Play live video.", fcode);
            if (pub == "live1" && currenContent=="Conference")
            {
                liveplay("live1C", "play", 2);
            }
            if (pub == "live1C" && currenContent == "Conference") {
                showhide("btnConfSwitchPlay", "none");
                showhide("btnConfSwitchPub", "none");
                
            }
            break;
        case 5003:
            //play file started
            showhide(pub + '_playbtn', 'none');
            showhide(pub + '_stopbtn', 'block');
            playerMsg(pub, "Play record.", fcode);
            break;
        case -5012:
            playerMsg(pub, "Stream not starter or already ended.", fcode);
            if (pub == "live1C" && currenContent == "Conference") {
                showhide("btnConfSwitchPlay", "block");
                showhide("btnConfSwitchPub", "block");
            }

            //stream not active
            break;
        case -5013:
            playerMsg(pub, "Record not found.", fcode);
            //stream not active
            break;
            //
        case 5101:
            playerMsg(pub, "Server disconnected", fcode);
            //server disconnected
            break;
        case 5102:
            playerMsg(pub, "Stop. Click 'Play' to continue", fcode);
            //  showhide(pub + '_playbtn', 'block');
            //  showhide(pub + '_stopbtn', 'none');

            //stream disconnected - stop
            break;
            //conference ----------------------------------------------

        case 7000:
            //meeting created
            playerMsg(pub, "Meeting created", fcode);
            break;
        case 7001:
            playerMsg(pub, "Ready. On air.", fcode);
            showhide("chat_block", "block");
            break;
        case -7100:
            playerMsg(pub, "Error on create meeting", fcode);
        case -7101:
            playerMsg(pub, "User in other meeting", fcode);
            break;
        case 9001:
            playerMsg(pub, fstring, fcode);
            break;
        case 8000:
            playerMsg(pub, fstring, 9001);
            break;
        case 99999:
            alert(fstring);
            break;
        case 123456:
            break;
        case 9988:
            //alert(fstring);
            showhide("MaxConBlock", "block");
            break;

            
    }

}
function sendCamParam(pname, setval, myname)
{
    var flashPlayer = gete(pname);
    if (null != flashPlayer) {
      
      
        flashPlayer.setCamParam(setval);
    }
    //alert(myname);
    //showhide(myname, "none");

}
function CheckPasswordContent(_onlineContentId, passI, password) {
    gete('msg_pass').style.display = "none";
    var v = gete(passI);
    var _password = "";
    if (!v)
        v = document.getElementsByName(passI);
    if (v)
        _password = v.value;


    $.ajax({
        type: "POST",
        url: window.MAIN_WEB_PATH + "Ajax/CheckPasswordContent",
        dataType: "json",
        data: { onlineContentId: _onlineContentId, password: _password },
        success: function (data, textStatus, jqXHR) {
            if (data == 'true') {
                showhide('mainblock1', 'block');
                showhide('mainblock0', 'none');
                showhide('mainblock2', 'block');
                liveplay("live1", "play", 3);
            }
            else {
                if (v)
                    v.value = "";
                gete('msg_pass').style.display = "block";
            }
            return;
        },
        error: function (data, textStatus, jqXHR) { return; }

    });

}
function setContentDsc(_onlineContentId) {
    var v = gete("contentDscInp");
    var ts = "";
    if (!v)
        return;
    ts = v.value;

    $.ajax({
        type: "POST",
        url: window.MAIN_WEB_PATH + "Ajax/setContentDsc",
        dataType: "json",
        data: { onlineContentId: _onlineContentId, dsctext: ts },
        success: function (data, textStatus, jqXHR) {
            return;
        },
        error: function (data, textStatus, jqXHR) { return; }

    });

}

function changeVid(pname, vidid) {
    var flashPlayer = gete(pname);
    if (null != flashPlayer) {
        flashPlayer.changeVid(vidid);
    }
}
//preview players
var frameid = "";
var waitclos = null;
function noframe() {
    liveplay("prePLAY", "stop");
      clearTimeout(waitclos);
    waitclos = null;
    //frameid = "";
}
var xxxp = '0';
function goframe(_obj, nid) {
    xxxp = nid;
    if (frameid == _obj)
        return;
    if (waitclos != null)
        return;
    liveplay("prePLAY", "stop");
    var v = gete("prePLAYBlock");
    var obj = gete(_obj);
    if (v) {

        obj.onmouseover = "return;";
        var pos = getOffset(obj);
        frameid = _obj;
        //getAbsolutePosition(obj);
        v.style.display = "block";
        v.style.left = pos.left + 'px';
        v.style.top = pos.top + 'px';

    }
    
    setTimeout("pp('prePLAY')", 1000);

}
function pp(o) {
    changeVid(o, xxxp);
}
function getOffset(elem) {
    return getOffsetSum(elem)
    if (elem.getBoundingClientRect) {
        return getOffsetRect(elem)
    } else {
        return getOffsetSum(elem)
    }
}
function getOffsetRect(elem) {
    // (1)
    var box = elem.getBoundingClientRect()

    // (2)
    var body = document.body
    var docElem = document.documentElement

    // (3)
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft

    // (4)
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0

    // (5)
    var top = box.top + scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft

    return { top: Math.round(top), left: Math.round(left) }
}
function getOffsetSum(elem) {
    var top = 0, left = 0
    while (elem) {

        top = top + parseFloat(elem.offsetTop)
        left = left + parseFloat(elem.offsetLeft)

        elem = elem.offsetParent
        if (elem.id == "middle") {
            elem = null
        }

        //elem.style.backgroundColor = "#f00"
        //elem = null;

    }

    return { top: Math.round(top), left: Math.round(left) }
}
function confToPublish() {
    liveplay("live1C", "stop", 1);
    var dp = gete("conf_player_div");
    var dv = gete("conf_pub_div");
    
    if (dp && dv) {
        
        dp.style.display = "none";
        dv.style.display = "block";
        setTimeout("swPublish(1)", 2000);
    }
}
function swPublish(v) {

    setPass("meet");
    var flashPlayer = gete("meet");
    if (null != flashPlayer && flashPlayer.publishVideo) {

        flashPlayer.publishVideo();
    }
    else {
        if (v == 1)
            setTimeout("swPublish(0)", 1000);
    }

}
function confToPlay() {
    var dp = gete("conf_player_div");
    var dv = gete("conf_pub_div");
    if (dp && dv) {
        dv.style.display = "none";
        dp.style.display = "block";
        
    }
    liveplay("live1C", "play", 2);
}
function switchConf() {
   
    var dv = gete("conf_pub_div");
    
    if (dv)
    {
     //   var ss = "publishCamera('meet')";
        if (dv.style.display.toLowerCase() != "block") {
            confToPublish();
 //           setTimeout(ss, 2000);
        }
        else {
            unpublishCamera("meet");
            confToPlay();
        }
    }
}
var lastview = 0;
function addView(onlineContentId, userId, tp) {
    if (lastview != 0)
        return;
    lastview = 1;
    $.ajax({
        type: "POST",
        url: window.MAIN_WEB_PATH + "Ajax/addView",
        dataType: "json",
        data: { onlineContentId: onlineContentId, userId: userId, tp:tp },
        success: function (data, textStatus, jqXHR) {return;},
        error: function (data, textStatus, jqXHR) { return; }
    });
}
function disconnectflash(pname)
{
    var flashPlayer = gete(pname);
    if (null != flashPlayer && flashPlayer.disconnect) {
        flashPlayer.disconnect();
    }
}
function confcancelPublishing(onlineContentId) {

    disconnectflash("meet");
    $.ajax({
        type: "POST",
        url: window.MAIN_WEB_PATH + "Ajax/cancelPublishing",
        dataType: "json",
        data: { onlineContentId: onlineContentId },
        success: function (data, textStatus, jqXHR) { setTimeout('window.location.href="/cabinet/online"', 1000); },
        error: function (data, textStatus, jqXHR) { return; }
    });
}



